// index.js
import { photoService } from '../../services/photo'

Page({
  data: {
    slides: [],         // 轮播图数据
    leftPhotos: [],     // 左列图片
    rightPhotos: [],    // 右列图片
    page: 1,           // 当前页码
    loading: false,    // 是否正在加载
    noMore: false      // 是否没有更多数据
  },

  onLoad() {
    this.loadInitialData()
    // 添加事件监听
    wx.eventChannel.on('photoUploaded', this.refreshPhotos.bind(this));
  },

  onUnload() {
    // 记得在页面卸载时移除事件监听
    wx.eventChannel.off('photoUploaded');
  },

  // 加载初始数据
  async loadInitialData() {
    try {
      // 加载轮播图
      const slides = await photoService.getSlides()
      this.setData({ slides })

      // 加载第一页图片
      await this.loadPhotos()
    } catch (error) {
      console.error('加载数据失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    }
  },

  // 加载图片列表
  async loadPhotos() {
    if (this.data.loading || this.data.noMore) return

    try {
      this.setData({ loading: true })
      
      const res = await photoService.getPhotos(this.data.page)
      
      // 将新图片分配到左右两列
      const { leftPhotos, rightPhotos } = this.data
      res.list.forEach((photo, index) => {
        if (index % 2 === 0) {
          leftPhotos.push(photo)
        } else {
          rightPhotos.push(photo)
        }
      })

      this.setData({
        leftPhotos,
        rightPhotos,
        page: this.data.page + 1,
        noMore: !res.hasMore
      })
    } catch (error) {
      console.error('加载图片失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  // 预览图片
  previewImage(e) {
    const { url } = e.currentTarget.dataset
    wx.previewImage({
      current: url,
      urls: [url]
    })
  },

  // 处理点赞
  async handleLike(e) {
    const id = e.currentTarget.dataset.id;
    // 获取当前数据
    const { leftPhotos, rightPhotos, slides } = this.data
    
    // 找到要更新的照片索引
    const leftIndex = leftPhotos.findIndex(item => item.id === id);
    const rightIndex = rightPhotos.findIndex(item => item.id === id);
    
    try {
      await photoService.likePhoto(id)
      
      // 更新轮播图中的赞数
      const slideIndex = slides.findIndex(item => item.id === id)
      if (slideIndex !== -1) {
        const newSlides = [...slides];
        newSlides[slideIndex] = {
          ...newSlides[slideIndex],
          likes: newSlides[slideIndex].likes + 1,
          isLiked: true
        };
        this.setData({ slides: newSlides })
      }

      // 更新瀑布流中的点赞数
      if (leftIndex !== -1) {
        const newLeftPhotos = [...leftPhotos];
        newLeftPhotos[leftIndex] = {
          ...newLeftPhotos[leftIndex],
          likes: newLeftPhotos[leftIndex].likes + 1,
          isLiked: true,
          animating: true
        };
        this.setData({ leftPhotos: newLeftPhotos });
        
        setTimeout(() => {
          newLeftPhotos[leftIndex].animating = false;
          this.setData({ leftPhotos: newLeftPhotos });
        }, 300);
      }

      if (rightIndex !== -1) {
        const newRightPhotos = [...rightPhotos];
        newRightPhotos[rightIndex] = {
          ...newRightPhotos[rightIndex],
          likes: newRightPhotos[rightIndex].likes + 1,
          isLiked: true,
          animating: true
        };
        this.setData({ rightPhotos: newRightPhotos });
        
        setTimeout(() => {
          newRightPhotos[rightIndex].animating = false;
          this.setData({ rightPhotos: newRightPhotos });
        }, 300);
      }

    } catch (error) {
      console.error('点赞失败:', error)
      wx.showToast({
        title: '点赞失败',
        icon: 'none'
      })
    }
  },

  // 下拉刷新
  async onPullDownRefresh() {
    try {
      this.setData({ loading: true })
      // 重新加载数据
      await this.loadInitialData()
      wx.stopPullDownRefresh()
    } catch (error) {
      console.error('刷新失败:', error)
      wx.showToast({
        title: '刷新失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  async onReachBottom() {
    if (this.data.loading || this.data.noMore) return
    
    try {
      this.setData({ loading: true })
      await this.loadMoreData()
    } catch (error) {
      console.error('加载更多失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  // 加载更多数据
  async loadMoreData() {
    try {
        const photos = await photoService.getPhotos(this.data.page)
        
        if (photos.list.length === 0) {
            this.setData({ noMore: true })
            return
        }
        
        // 将新图片分配到左右两列
        const { leftPhotos, rightPhotos } = this.data
        photos.list.forEach((photo, index) => {
            if (index % 2 === 0) {
                leftPhotos.push(photo)
            } else {
                rightPhotos.push(photo)
            }
        })
        
        this.setData({
            leftPhotos,
            rightPhotos,
            page: this.data.page + 1,
            noMore: photos.list.length < 10
        })
    } catch (error) {
        throw error
    }
  },

  // 刷新照片列表的方法
  refreshPhotos() {
    // 重置数据状态
    this.setData({
        leftPhotos: [],
        rightPhotos: [],
        page: 1,
        noMore: false
    });
    // 重新加载数据
    this.loadInitialData();
  }
})
